/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import android.content.Intent;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import utsc.apps.utschedule.R;
import utsc.apps.utschedule.UTSCheduleApp;
import utsc.apps.utschedule.classes.Assignment;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.classes.Exam;
import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.services.TimetableDataService;
import utsc.apps.utschedule.ui.interfaces.TimetableActivity;
import utsc.apps.utschedule.util.AppUtils;
import utsc.apps.utschedule.util.TimetableHelper;
import utsc.apps.utschedule.util.Validator;
import utsc.apps.utschedule.util.database.DatabaseManager;
import utsc.apps.utschedule.widget.ButtonsLayout;
import utsc.apps.utschedule.widget.ObjectButtonView;

/**
 * This activity shows the detail information about a {@link Course course}.
 *
 */
public class CourseDetailActivity extends GenericDetailActivity implements OnClickListener{

	public static final String TAG="CourseDetailActivity";
	private Course _course;
	public static final String REQUEST_COURSE_KEY="requestCourse";
	private TextView _txtSection;
	private TextView _txtShortTitle;
	private TextView _txtLocation;
	private TextView _txtWeekDay;
	private TextView _txtStartTime;
	private TextView _txtEndTime;
	private TextView _txtOddWeeks;
	private TextView _txtTutorial;
	private TextView _txtInstructor;
	private TextView _txtWeight;
	private boolean _updated=true;
	private int _courseID=-1;
	private ButtonsLayout _assignmentBtnsLayout;
	private LinearLayout _emptyAssignmentLayout;
	private ButtonsLayout _examBtnsLayout;
	private LinearLayout _emptyExamLayout;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_course_detail);
		Intent requestIntent=getIntent();
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		if (requestIntent!=null) {
			_courseID=requestIntent.getIntExtra(REQUEST_COURSE_KEY,-1);
			_course=DatabaseManager.getInstance(getApplicationContext()).getCourse(_courseID);
			//checks whether or not we got the course object
			if (_course!=null) {
				_color=_course.get_color();
				setupHeader();
				setupDetailContent();
			}else {
				Toast.makeText(this, AppUtils.ERROR_MESSAGE_COURSE_NOT_FOUND, Toast.LENGTH_LONG).show();
				finish();
			}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//if not updated, refresh the view
		if (!_updated) {
			DatabaseManager.getInstance(getApplicationContext()).refreshCourse(_course);
			_color=_course.get_color();
			
			setupHeader();
			setupDetailContent();
			_updated=true;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getSupportMenuInflater().inflate(R.menu.detail_menu_items, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onOptionsItemSelected(item);
		int id=item.getItemId();
		//handle different option item clicks
		switch (id) {
		case R.id.delete:
			DatabaseManager.getInstance(this).deleteCourse(_course);
			 Intent i= new Intent(this, TimetableDataService.class);
			 i.putExtra(TimetableDataService.REQUEST_REFRESH, TimetableDataService.REFRESH_COURSES);
			 startService(i);
	         finish();   
			break;
		case R.id.edit:
			Intent editCourse=new Intent(this, CourseFormActivity.class);
			editCourse.putExtra(REQUEST_COURSE_KEY, _course.get_courseID());
			startActivityForResult(editCourse, TimetableActivity.RESULT_UPDATE_COURSE);
			break;
		case android.R.id.home:
			finish();
		default:
			break;
		}
		return true;
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg1==RESULT_OK) {
			if (arg2!=null) {
				_courseID=arg2.getIntExtra("CourseFormResult",_courseID);
				_updated=false;
			}
		}
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		intent.putExtra("RequestCode", requestCode);
		intent.putExtra("RequestResult", true);
		super.startActivityForResult(intent, requestCode);
	}
	
	@Override
	protected void setupHeader() {
		_detailHeader=(LinearLayout) findViewById(R.id.detail_header);
		if (_detailHeader!=null) {
			TextView title=(TextView) _detailHeader.findViewById(R.id.detail_header_title);
			TextView subTitle=(TextView) _detailHeader.findViewById(R.id.detail_header_subtitle);
			LinearLayout detailColorIcon=(LinearLayout) _detailHeader.findViewById(R.id.detail_color_icon);
			
			UTSCheduleApp app=(UTSCheduleApp) getApplication();
			Timetable timetable=app.get_currentActiveTimetable();
			
			title.setText(_course.get_courseCode());
			subTitle.setText(timetable.toString());
			
			WeakReference<LayerDrawable> bg=AppUtils.getColorCustomizableDrawable(getApplicationContext(), R.drawable.bezel_border_bg, _color, 0, AppUtils.ALPHA);
			detailColorIcon.setBackgroundDrawable(bg.get());
			
			WeakReference<LayerDrawable> headerBg=new WeakReference<LayerDrawable>((LayerDrawable) getResources().getDrawable(R.drawable.black_bg));
			if (!_course.is_tutorial()) {
				headerBg.get().getDrawable(1).setAlpha(0);
			}
			_detailHeader.setBackgroundDrawable(headerBg.get());
		}
	}

	@Override
	protected void setupDetailContent() {
		_txtSection=(TextView) findViewById(R.id.frm_txt_section);
		_txtShortTitle=(TextView) findViewById(R.id.frm_txt_shorttitle);
		_txtLocation=(TextView) findViewById(R.id.frm_txt_location);
		_txtWeekDay=(TextView) findViewById(R.id.frm_txt_weekday);
		_txtStartTime=(TextView) findViewById(R.id.frm_txt_starttime);
		_txtEndTime=(TextView) findViewById(R.id.frm_txt_endtime);
		_txtOddWeeks=(TextView) findViewById(R.id.frm_txt_oddweeks);
		_txtTutorial=(TextView) findViewById(R.id.frm_txt_tutorial);
		_txtInstructor=(TextView) findViewById(R.id.frm_txt_instructor);
		_txtWeight=(TextView) findViewById(R.id.frm_txt_weight);
		
		String section=_course.get_section();
		String shortTitle=_course.get_shortName();
		String location=_course.get_location();
		String weekday=TimetableHelper.getWeekdayString(_course.get_day()+1);
		String startTime=TimetableHelper.getFormattedString(_course.get_startTime(), TimetableHelper.TYPE_TIME);
		String endTime=TimetableHelper.getFormattedString(_course.get_endTime(), TimetableHelper.TYPE_TIME);
		String oddWeeks=Integer.toString(_course.get_oddWeeks());
		String tutorial=_course.is_tutorial()?"Yes":"No";
		String instructor=_course.get_instructor();
		
		_txtSection.setText(Validator.checkNonRequiredNull(section)?section:DEFAULT_TEXT);
		_txtShortTitle.setText(Validator.checkNonRequiredNull(shortTitle)?shortTitle:DEFAULT_TEXT);
		_txtLocation.setText(location);
		_txtWeekDay.setText(weekday);
		_txtStartTime.setText(startTime);
		_txtEndTime.setText(endTime);
		_txtOddWeeks.setText(Validator.checkNonRequiredNull(oddWeeks)?oddWeeks:DEFAULT_TEXT);
		_txtTutorial.setText(tutorial);
		_txtInstructor.setText(Validator.checkNonRequiredNull(instructor)?instructor:DEFAULT_TEXT);
		_txtWeight.setText(String.valueOf(_course.get_weight()));
		
		setupAssignments();
		
		setupExams();
		
	}
	
	/**
	 * Setup the Assignment section of the current course.
	 */
	private void setupAssignments() {
		_assignmentBtnsLayout=(ButtonsLayout) findViewById(R.id.assignments_btns_layout);
		_emptyAssignmentLayout=(LinearLayout) findViewById(R.id.empty_assignment_layout);
		View assignMentInfoView=findViewById(R.id.frm_assignment_info);
			if (assignMentInfoView.getVisibility()==View.GONE) {
				assignMentInfoView.setVisibility(View.VISIBLE);
			}
			//get the list of assignments by giving the parent course id
			ArrayList<Object> assignmentObjs=new ArrayList<Object>(DatabaseManager.getInstance(this).queryAssignment(_course.get_parentCourse().get_courseID()));
			if (!assignmentObjs.isEmpty()) {
				_assignmentBtnsLayout.set_onObjectButtonClickedListener(this);
				_assignmentBtnsLayout.set_items(assignmentObjs);
				_emptyAssignmentLayout.setVisibility(View.GONE);
				_assignmentBtnsLayout.setVisibility(View.VISIBLE);
				
			}else {
				_emptyAssignmentLayout.setVisibility(View.VISIBLE);
				_assignmentBtnsLayout.setVisibility(View.GONE);
			}
	}
	
	/**
	 * Setup the Exam section of the current course.
	 */
	private void setupExams() {
		_examBtnsLayout=(ButtonsLayout) findViewById(R.id.exams_btns_layout);
		_emptyExamLayout=(LinearLayout) findViewById(R.id.empty_exam_layout);
		View examInfoView=findViewById(R.id.frm_exam_info);
			if (examInfoView.getVisibility()==View.GONE) {
				examInfoView.setVisibility(View.VISIBLE);
			}
			//get the list of exams by giving the parent course id
			ArrayList<Object> examObj=new ArrayList<Object>(DatabaseManager.getInstance(this).queryExams(_course.get_parentCourse().get_courseID()));
			if (!examObj.isEmpty()) {
				_examBtnsLayout.set_onObjectButtonClickedListener(this);
				_examBtnsLayout.set_items(examObj);
				_emptyExamLayout.setVisibility(View.GONE);
				_examBtnsLayout.setVisibility(View.VISIBLE);
				
			}else {
				_emptyExamLayout.setVisibility(View.VISIBLE);
				_examBtnsLayout.setVisibility(View.GONE);
			}
	}

	@Override
	public void onClick(View v) {
		//handle the click event on both assignment section and exam section
		if (v instanceof ObjectButtonView) {
			Object object=((ObjectButtonView)v).get_object();
			//open the associated detail view by checking the object type
			if (object instanceof Assignment) {
				final Assignment assignment=(Assignment)object;
				if (assignment!=null) {
					Intent updateAssignmentIntent=new Intent(this,AssignmentDetailActivity.class);
					updateAssignmentIntent=new Intent(this,AssignmentDetailActivity.class);
					updateAssignmentIntent.putExtra(Assignment.EXPIRED, assignment.is_expired());
					updateAssignmentIntent.putExtra(Assignment.COURSE, assignment.get_course().get_courseID());
					updateAssignmentIntent.putExtra(Assignment.ASSUID, assignment.get_AssUID());
					startActivityForResult(updateAssignmentIntent, TimetableActivity.RESULT_UPDATE_ASSIGNMENT);
				}
			}else {
				final Exam exam=(Exam) object;
				Intent updateExamIntent=exam.getObjectIntent();
	        	updateExamIntent.setClass(this, ExamFormActivity.class);
				updateExamIntent.putExtra("CourseExam", exam.get_course().get_courseID());
				updateExamIntent.putExtra("RequestCode", TimetableActivity.RESULT_UPDATE_EXAM);
				startActivityForResult(updateExamIntent, TimetableActivity.RESULT_UPDATE_EXAM);
			}
			
		}
		
	}
	
	

}
